<template>
  <div>
    <!-- 此处是element ui的面包屑部分 breadcrumb -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片管理 -->
    <el-card class="box-card">
      <!-- 带搜索 输入框 -->

      <!-- 设置分兰间隔 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryInfo.query"
            clearable
          >
            <el-button slot="append" icon="el-icon-search" @click="getUserlist()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button round type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!--用户列表区域 -->
      <el-table :data="userlist" border stripe>
        <!-- 索引列  type = "index" -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <!-- 状态默认不是按钮 需要数据结构改造 使用作用域插槽,prop可以去掉-->
        <el-table-column label="状态" prop="mg_state">
          <!-- 这里使用插值 
         <template slot-scope="scope">{{scope.row}}</template
         最新方法是 v-slot 替代  slot-scope
         >
          -->
          <template v-slot:default="scope">
            <!-- element ui的开关组件 
            绑定到具体某一行的.由mg_state控制
            -->
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#C0CCDA"
              @change="userStateChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <!-- 操作使用作用插槽 -->
          <template v-slot:default="scope">
            <!-- 修改 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="修改角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="small"
                @click="showEditDialog(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <!-- 删除 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="删除角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-delete"
                size="small"
                @click="removeUserById(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <!-- 角色调整按钮 -->
            <el-tooltip effect="dark" content="角色分配" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-share" size="small"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页设置区域 
       @size-change 当前页面变化监听
       @current-change 页码变换监听
      -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 3, 4]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDilagClosed">
      <!-- 主题区域 -->
      <!-- 添加用户对话框 -->
      <el-form
        :model="addForm"
        status-icon
        :rules="addFormRules"
        ref="addFormRef"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改信息对话框 -->
    <el-dialog title="修改信息" :visible.sync="editDialogVisble" width="30%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
      </el-form>
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
        <el-form-item label="邮箱">
          <el-input v-model="editForm.email" prop="email"></el-input>
        </el-form-item>
      </el-form>
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
        <el-form-item label="手机号">
          <el-input v-model="editForm.mobile" prop="mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisble = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>



<script>
export default {
  //发起请求.获取用户列表

  //用到的参数
  data() {
    //验证手机
    var checkeMobile = (rule, value, cb) => {
      //正则表达式
      let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (reg.test(value)) {
        cb()
      } else {
        cb(new Error('手机号码格式不正确'))
      }
    }
    //验证邮箱
    var checkemail = (rule, value, cb) => {
      //正则表达式
    }
    return {
      queryInfo: {
        query: '',
        //当前页
        pagenum: 1,
        //当前页面显示多少页
        pagesize: 2
      },
      userlist: [],
      total: 0,
      value: true,
      addDialogVisible: false,
      //用户表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      //用户表单数据验证
      addFormRules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 8,
            message: '6-8个字符',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机',
            trigger: 'blur'
          },
          {
            validator: checkeMobile,
            trigger: 'blur'
          }
        ]
      },
      //控制修改对话框隐藏及显示
      editDialogVisble: false,
      //查询到的需要修改的用户数据
      editForm: {},
      //修改时的验证规则,此处没有添加,对比添加用户
      editFormRules: {
        email: [
          {
            required: true
          }
        ],
        mobile: [
          {
            required: true
          }
        ]
      }
    }
  },
  //定义生命周期函数
  created() {
    this.getUserlist()
  },
  //定义获取用户列表数据
  methods: {
    async getUserlist() {
      let { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败 ')
      }
      this.userlist = res.data.users
      this.total = res.data.total
    },
    //监听页面pagesize的变化函数
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserlist()
    },
    //监听页码的变化函数
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserlist()
    },
    //状态按钮控制
    async userStateChange(userinfo) {
      //此处根据文档,发起put请求 为了拼接参数,将单引号修改为模板字符串,` ` 反引号
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        //如果更新失败,页面的状态也需要调整为之前的状态
        this.userinfo = !this.userinfo
        return this.$message.error('状态更新失败')
      }
      this.$message.success('更新ok')
    },
    //重置添加用户的输入框,每次关闭后清除上次的数据
    addDilagClosed() {
      this.$refs.addFormRef.resetFields()
    },
    //添加新用户
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.status !== 201) {
          this.$message.error('添加用户失败')
        }

        this.$message.success('添加用户成功!!!')
        //关闭用户对话框
        this.addDialogVisible = false
        //刷新列表
        this.getUserlist()
      })
    },
    //修改对话框
    async showEditDialog(id) {
      //根据id获取用户数据
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息错误')
      }
      this.editForm = res.data
      console.log(this.editForm)
      this.editDialogVisble = !this.editDialogVisble
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    //修改用户信息及提交,需要先进性验证才能提交
    editUserInfo() {
      this.$refs.editFormRef.validate(async validResult => {
        if (!validResult) return
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改用户信息失败')
        }
        this.editDialogVisble = !this.editDialogVisble
        this.getUserlist()
      })
    },
    async removeUserById(id) {
      const res = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(async () => {
         const {data : res} = await this.$http.delete('users/' + id)
        this.getUserlist()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>




<style lang="less" scoped>
</style>